import { ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import router from '@/router/index'
import { usePermissionStore } from '@/store/modules/permission'
import useCurrentRoleStore from '@/store/modules/current-role'

let socket: WebSocket | null = null
let callbackEvent: any = null
function initWebSocket(event, api, errorCallback?: () => void) {
  let protocol = `wss://${window.location.hostname}/api` // 默认是线上的域名
  if (window.location.protocol === 'http:') {
    // 配置开发域名
    if (
      window.location.hostname.startsWith('127.0.0.1') ||
      window.location.hostname.startsWith('localhost') ||
      window.location.hostname.startsWith('192.168.')
    ) {
      protocol = 'ws://192.168.3.52:7116'
    } else {
      // 线上http域名带端口号
      protocol = `ws://${window.location.hostname}:${window.location.port}/api`
    }
  }
  const socketURL = `${protocol}${api}`
  socket = new WebSocket(socketURL)
  callbackEvent = event
  const UserStore = useUserStore()
  socket.addEventListener('open', () => {
    // e
  })

  socket.addEventListener('message', (event) => {
    try {
      const message = JSON.parse(event.data)
      // e
      // 处理收到的消息
      if (message.code == 40102) {
        UserStore.token = null
        UserStore.roles = []
        UserStore.row = {
          tokenValue: null, //登录token
          expireIn: null, //过期时间
          tokenStartTime: null, //登录当前时间
          refreshToken: null, //刷新token
          tokenName: null,
        }
        closeWebSocket()
        ElMessageBox.confirm(message.message, '提示', {
          confirmButtonText: '确定',
          type: 'error',
          showCancelButton: false,
          showClose: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
        }).then(async () => {
          usePermissionStore().clearRoutes()
          useCurrentRoleStore().clearCurrentRole()
          router.push({ path: '/login/index' })
        })
      } else {
        callbackEvent(message)
      }
    } catch (error) {
      callbackEvent(event)
    }
  })

  socket.addEventListener('close', () => {
    // e
  })

  socket.addEventListener('error', (error) => {
    if (errorCallback) {
      errorCallback()
    }
    // e
  })
}
//  处理收到的消息
function websocketonmessage(message) {
  return message
}
// 发送消息
function sendWebSocket(message: string) {
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.send(message)
  } else {
    console.error('WebSocket连接未打开')
  }
}
// 关闭 WebSocket 连接
function closeWebSocket() {
  if (socket) {
    socket.close()
  }
}

export { initWebSocket, sendWebSocket, closeWebSocket, websocketonmessage }
